package com.example.zhengjiyu

import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.appcompat.app.AlertDialog
import android.widget.Toast
import java.io.BufferedReader
import java.io.InputStreamReader

class WordListFragment : Fragment() {

    private lateinit var recyclerView: RecyclerView
    private val wordList = mutableListOf<String>()
    private lateinit var wordAdapter: WordAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_word_list, container, false)
        recyclerView = view.findViewById(R.id.wordRecyclerView)
        recyclerView.layoutManager = LinearLayoutManager(context)

        loadWordsFromFile()  // 加载单词列表

        wordAdapter = WordAdapter(wordList) { position ->
            showDeleteConfirmationDialog(position)
        }
        recyclerView.adapter = wordAdapter
        return view
    }

    // 显示删除确认对话框
    private fun showDeleteConfirmationDialog(position: Int) {
        AlertDialog.Builder(requireContext())
            .setTitle("删除单词")
            .setMessage("你确定要删除这个单词吗？")
            .setPositiveButton("删除") { _, _ ->
                removeWord(position)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    // 从列表中删除单词并更新文件
    private fun removeWord(position: Int) {
        val wordToRemove = wordList[position]
        wordList.removeAt(position)
        wordAdapter.notifyItemRemoved(position)
        saveUpdatedWordsToFile()  // 更新文件
        Toast.makeText(context, "单词已删除", Toast.LENGTH_SHORT).show()
    }

    // 加载单词列表
    private fun loadWordsFromFile() {
        wordList.clear()
        try {
            val fileInputStream = requireContext().openFileInput("words.txt")
            val reader = BufferedReader(InputStreamReader(fileInputStream))
            var line: String? = reader.readLine()
            while (line != null) {
                wordList.add(line)
                line = reader.readLine()
            }
            reader.close()
            fileInputStream.close()
        } catch (e: Exception) {
            Toast.makeText(context, "无法加载单词", Toast.LENGTH_SHORT).show()
        }
    }

    // 将更新后的单词列表保存到文件
    private fun saveUpdatedWordsToFile() {
        try {
            val fileOutputStream = requireContext().openFileOutput("words.txt", android.content.Context.MODE_PRIVATE)
            for (word in wordList) {
                fileOutputStream.write((word + "\n").toByteArray())
            }
            fileOutputStream.close()
        } catch (e: Exception) {
            Toast.makeText(context, "无法更新文件", Toast.LENGTH_SHORT).show()
        }
    }
}
